import { createStore } from "vuex";
import { homeReq } from "@/api/home.js";
import { logoutReq } from "@/api/header.js";
import { removeToken } from "@/utils/token.js";
import {success} from '@/utils/messageUtils'
import {router} from '@/router/index.js'
import { useCookies } from '@vueuse/integrations/useCookies'

// 创建一个新的 store 实例
const store = createStore({
  state() {
    return {
      projectTitile: "小高低代码平台",
      // 用户信息
      userInfo: {
        username: "",
        realName: "",
      },
      // 菜单
      leftMenuTree: [],
      // 路由
      routers: [],
      // 按钮权限
      perms: [],
      activeRoute: "/welcome",
      // 菜单图标
      menuIcon: ''
    };
  },
  mutations: {
    // 记录用户信息
    SET_USERINFO(state, userInfo) {
      state.userInfo.username = userInfo.username;
      state.userInfo.realName = userInfo.realName;
    },
    // 记录菜单
    SET_MENUS(state, menus) {
      state.leftMenuTree = menus;
    },
    // 记录路由
    SET_ROUTERS(state, routers) {
      state.routers = routers;
    },
    // 记录权限
    SET_PERMS(state, perms) {
      state.perms = perms;
    },
    // 记录激活的路由
    SET_ACTIVE_ROUTE(state, activeRoute) {
      state.activeRoute = activeRoute;
    },
    // 改变添加菜单时，图标组件的值
    SET_MENU_ICON(state, currentIcon) {
      state.menuIcon = currentIcon
    }
  },
  actions: {
    // 获取当前用户登录信息
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        // 存储用户信息
        homeReq()
          .then((res) => {
            commit("SET_USERINFO", res.data.sysUserResponse);
            commit("SET_MENUS", res.data.menuTree);
            commit("SET_ROUTERS", res.data.routerList);
            commit("SET_PERMS", res.data.buttonPermList);
            resolve(res);
          })
          .catch((err) => reject(err));
      });
    },
    // 退出登录
    logout({ commit }) {
      logoutReq().then(res => {
        if (res.code == 200) {
          // 清除token
          removeToken();
          // 清除用户
          commit("SET_USERINFO", { realName: "", username: "" });
          // 清除菜单
          commit("SET_MENUS", []);
          // 清除路由
          commit("SET_ROUTERS", []);
          // 清除权限
          commit("SET_PERMS", []);
          // 清除cookie中存储的上一次的路由
          const cookie = useCookies()
          cookie.remove("fromURL")
          router.push("/login");
          success("退出登录！");
        }
      })
    },
  },
});
export default store;
